﻿using Core.Language;
using Core.Utility.Helper;
using RulesEngine.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Core.ValidateRules.Lib
{
    /// <summary>
    /// 最大值，规则引擎基础验证属性
    /// </summary>
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
    public class ValidateRulesMaxLengthAttribute : MaxLengthAttribute
    {
        /// <summary>
        /// 本地化错误信息字符串
        /// </summary>
        protected string LocalizeErrorMessageString
        {
            get
            {
                if (!string.IsNullOrEmpty(ErrorMessageString))
                {
                    return LanguageResource.GetResourceValue(ErrorMessageString).GetValueOrDefault();
                }
                else
                {
                    return ErrorMessageString;
                }
            }
        }

        /// <summary>
        ///     Initializes a new instance of the <see cref="MaxLengthAttribute" /> class.
        ///     The maximum allowable length supported by the database will be used.
        /// </summary>
        public ValidateRulesMaxLengthAttribute()
            : base()
        {
        }

        /// <summary>
        ///     Initializes a new instance of the <see cref="MaxLengthAttribute" /> class.
        ///     The maximum allowable length supported by the database will be used.
        /// </summary>
        public ValidateRulesMaxLengthAttribute(int length)
            : base(length)
        {

        }

        /// <summary>
        /// 验证返回的最终结果，可通过该方法进行拦截，输出本地化后的对象
        /// </summary>
        /// <param name="value"></param>
        /// <param name="validationContext"></param>
        /// <returns></returns>
        protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
        {
            //拦截上下文对象中的DisplayName属性，做本地化转换
            // call overridden method.
            string localizeDisplayName = LanguageResource.GetResourceValue(validationContext.DisplayName).GetValueOrDefault();
            if (!IsValid(value))
            {
                string[]? memberNames = validationContext.MemberName is { } memberName
                    ? new[] { memberName }
                    : null;
                var result = new ValidationResult(string.Format(LocalizeErrorMessageString, localizeDisplayName, Length), memberNames);
                return result;
            }
            return ValidationResult.Success;
        }
    }
}
